package com.lhd.weibo.service.impl;

import com.lhd.weibo.exception.ServiceException;
import com.lhd.weibo.mapper.UserMapper;
import com.lhd.weibo.pojo.dto.UserLoginDTO;
import com.lhd.weibo.pojo.dto.UserRegDTO;
import com.lhd.weibo.pojo.entity.User;
import com.lhd.weibo.pojo.vo.UserVO;
import com.lhd.weibo.response.StatusCode;
import com.lhd.weibo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author lhd
 * date 2024/5/15
 * @apiNote
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Override
    public void reg(UserRegDTO userRegDTO) {
        log.info("userRegDTO:{}",userRegDTO);
        UserVO userVO = userMapper.selectByUsername(userRegDTO.getUsername());

        if (userVO != null) {
            //主业务如果遇到了问题,需要抛出业务层异常,而不是直接给前端返回结果
            //Controller层才是给前端返回结果的那一层
            throw new ServiceException(StatusCode.USERNAME_ALREADY_EXISTS);
        }

        User user = new User();
        user.setUsername(userRegDTO.getUsername());
        user.setPassword(userRegDTO.getPassword());
        user.setNickname(userRegDTO.getNickname());
        user.setCreated(new Date());

        userMapper.insert(user);
    }

    @Override
    public UserVO login(UserLoginDTO userLoginDTO) {
        log.info("userLoginDTO:{}",userLoginDTO);
        UserVO userVO = userMapper.selectByUsername(userLoginDTO.getUsername());
        if (userVO == null){
            throw new ServiceException(StatusCode.USERNAME_NOT_EXISTS);
        }

        if (!userVO.getPassword().equals(userLoginDTO.getPassword())){
            throw new ServiceException(StatusCode.PASSWORD_ERROR);
        }

        return userVO;
    }

}
